package com.settlement.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.constant.ExcelConstants;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.BillConfigImportListener;
import com.settlement.system.model.entity.SysBillColumn;
import com.settlement.system.model.query.BillColumnPageQuery;
import com.settlement.system.model.vo.BillConfigImportVO;
import com.settlement.system.service.SysBillColumnService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 标准账单字段对应关系 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-07
 */
@Tag(name = "标准账单字段对应关系")
@RestController
@RequestMapping("/api/v1/billColumn")
@RequiredArgsConstructor
public class SysBillColumnController {

    private final SysBillColumnService billColumnService;

    @Operation(summary = "导入标准账单配置表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> importTableConfig(@RequestParam("file") MultipartFile file) throws IOException {
        BillConfigImportListener listener = new BillConfigImportListener();
        EasyExcelFactory.read(file.getInputStream(), BillConfigImportVO.class, listener).sheet(0).doRead();
        List<BillConfigImportVO> rows = listener.getVos();
        // 保存数据
        billColumnService.importTableConfig(rows);
        return Result.success("导入成功");
    }

    @Operation(summary = "标准账单模板下载", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "标准账单导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = ExcelConstants.EXCEL_TEMPLATE_DIR + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "标准账单配置列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysBillColumn> getBillColumnPage(
            @ParameterObject BillColumnPageQuery queryParams
    ) {
        Page<SysBillColumn> result = billColumnService.getBillColumnPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "导出标准账单配置数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void exportUsers(HttpServletResponse response) throws IOException {
        String fileName = "标准账单配置.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<SysBillColumn> billColumnList = billColumnService.listAll();
        List<BillConfigImportVO> exportUserList = new ArrayList<>();
        for (SysBillColumn billColumn : billColumnList) {
            BillConfigImportVO vo = new BillConfigImportVO();
            BeanUtil.copyProperties(billColumn, vo);
            exportUserList.add(vo);
        }
        EasyExcel.write(response.getOutputStream(), BillConfigImportVO.class).sheet("标准账单配置")
                .doWrite(exportUserList);
    }
}
